package com.tutu.service.impl01;

import com.tutu.dao.CommodityDao;
import com.tutu.dao.SaleDao;
import com.tutu.entity.Commodity;
import com.tutu.entity.Sale;
import com.tutu.exception.NotEnoughException;
import com.tutu.service.BuyCommodityService;

/**
 * @Program: Spring_New
 * @Description:
 * @Author: JK.TuTu
 * @Create: 2022-09-15 21:10
 **/
public class BuyCommodityServiceImpl implements BuyCommodityService {
    //定义两个dao属性
    private SaleDao saleDao;
    private CommodityDao commDao;


    //添加注解
    /*@Transactional(
            //指定传播行为
            propagation = Propagation.REQUIRED,
            //指定隔离级别
            isolation = Isolation.DEFAULT,
            //指定需要回滚的异常
            rollbackFor = {NullPointerException.class, NotEnoughException.class})*/
    //@Transactional//属性可省略不写，全部按默认
    @Override
    public void buy(Integer cId, Integer nums) {
        //1.添加销售记录
        Sale sale = new Sale();//创建销售表实体类
        sale.setCid(cId);
        sale.setNums(nums);
        int result1 = saleDao.insertSale(sale);
        System.out.println(result1 > 0 ? "添加销售记录成功" : "添加销售记录失败");

        //2.进行验证
        Commodity oldComm = commDao.selectCommodity(cId);//查询指定编号的商品信息
        if (oldComm == null) {
            throw new NullPointerException("编号为" + cId + "的商品不存在");
        } else if (oldComm.getCount() < nums) {
            throw new NotEnoughException("编号为" + cId + "的商品库存不足");
        }

        //3.更新商品库存
        Commodity newComm = new Commodity();
        newComm.setId(cId);
        newComm.setCount(nums);
        int result2 = commDao.updateCount(newComm);
        System.out.println(result2 > 0 ? "更新商品库存成功" : "更新商品库存失败");
    }

    //通过set注入给saleDao属性赋值
    public void setSaleDao(SaleDao saleDao) {
        this.saleDao = saleDao;
    }

    //通过set注入给commDao属性赋值
    public void setCommDao(CommodityDao commDao) {
        this.commDao = commDao;
    }

}